# Create your views here.
import json

from django.db import connection
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework_simplejwt.tokens import RefreshToken

from accounts.models import MyUser


def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }


@csrf_exempt
def login_view(request):
    if request.method != 'POST':
        return JsonResponse({'error': 'Only POST method is allowed'}, status=405)

    try:
        data = json.loads(request.body)
        email = data.get('email')
        password = data.get('password')

        if not email or not password:
            return JsonResponse({'error': 'Email and password are required.'}, status=400)
        cursor = connection.cursor()
        sql = f"SELECT * FROM accounts_myuser WHERE email = '{email}' AND password = '{password}'"
        print(sql)
        cursor.execute(sql)
        rows = cursor.fetchall()
        print(rows)
        if len(rows) > 0:
            user = MyUser.objects.get(id=rows[0][0])  # 获取Django User对象
            token = get_tokens_for_user(user)
            return JsonResponse({'success': 1, 'token': token, 'user': rows[0][1]})
        else:
            return JsonResponse({'error': 'Invalid email or password.'}, status=401)

        # if user is not None:
        #     # 如果你使用 session 登录（比如本地测试或管理后台）
        #     # login(request, user)
        #
        #     # 模拟 token（实际项目建议返回 JWT）
        #     return JsonResponse({'success': 1, 'token': 'mocked-token-123', 'user': user.email})
        # else:
        #     return JsonResponse({'error': 'Invalid email or password.'}, status=401)

    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON format'}, status=400)


@csrf_exempt
def register_view(request):
    if request.method != 'POST':
        return JsonResponse({'error': 'Only POST method is allowed'}, status=405)

    try:
        data = json.loads(request.body)
        email = data.get('email')
        password = data.get('password')
        name = data.get('username')
        print(email, password, name)
        sql = f"SELECT * FROM accounts_myuser WHERE email = '{email}'"
        cursor = connection.cursor()
        cursor.execute(sql)
        rows = cursor.fetchall()
        if len(rows) > 0:
            return JsonResponse({'error': '该邮箱已被注册'}, status=400)
        else:
            sql = f"INSERT INTO accounts_myuser (email, password, name) VALUES ('{email}', '{password}', '{name}')"
            cursor.execute(sql)
            connection.commit()
            return JsonResponse({'success': 1, 'token': 'mocked-token-123', 'user': name})

    except Exception as e:
        print(e)
        return JsonResponse({'error': 'Invalid JSON format'}, status=400)
